//
//  NetworkAPI.m
//  MengTianXia
//
//  Created by zl on 2019/8/10.
//  Copyright © 2019 qttx. All rights reserved.
//

#import "NetworkManager.h"
#import "SDAVAssetExportSession.h"

@implementation NetworkManager

#pragma mark - 参数验签处理
/// 拼接请求参数字典
/// @param module 接口模块名
/// @param interface 接口编码
/// @param dataDict 请求参数
+ (NSDictionary *)setupParamsDictWithModule:(NSString *)module interface:(NSString *)interface dataDict:(NSDictionary *)dataDict {
    // 请求参数字典
    NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
    [paramsDict setObject:@"ios" forKey:@"source"];
    [paramsDict setObject:@"v1" forKey:@"version"];
    [paramsDict setObject:kCheckString(module) forKey:@"module"];
    [paramsDict setObject:kCheckString(interface) forKey:@"interface"];
    NSInteger timestamp = [[NSDate date] timeIntervalSince1970];
    [paramsDict setObject:@(timestamp) forKey:@"timestamp"];
    
    NSString *queryStr = [self dictToUrlParams:paramsDict];
    // 前后添加APP key
    NSString *appStr = [NSString stringWithFormat:@"%@%@%@", APPKey, queryStr, APPKey];
//    NSLog(@"拼接APP key:%@", appStr);
    // base64加密
    NSString *base64Str = [BWSecurities base64EncodeString:appStr];
//    NSLog(@"base64加密:%@", base64Str);
    // MD5加密
    NSString *md5Str = [BWSecurities md5EncryptWithString:base64Str];
//    NSLog(@"MD5加密:%@", md5Str);
    // 转小写
    NSString *resultStr = [md5Str lowercaseString];
//    NSLog(@"最终结果: %@", resultStr);
    
    [paramsDict setObject:resultStr forKey:@"sign"];
    if (dataDict != nil) {
        [paramsDict setObject:dataDict forKey:@"data"];
    }
    
    return paramsDict;
}


/// 字典转query字符串
+ (NSString *)dictToUrlParams:(NSDictionary *)dict {
    NSArray *keys = [dict allKeys];
    
    /// key与value组合
    NSMutableArray *tempArray = [NSMutableArray array];
    for (int i = 0; i < keys.count; i++) {
        NSString *key = keys[i];
        id value = [dict objectForKey:key];
        NSString *str = [NSString stringWithFormat:@"%@=%@", key, value];
        [tempArray addObject:str];
    }
    
    /// ASCII升序排列
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1, NSString *obj2){
        NSRange range = NSMakeRange(0, obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray = [tempArray sortedArrayUsingComparator:sort];
    
    /// 拼接字符串
    NSMutableString *paramsStr = [NSMutableString string];
    for (int j = 0; j < resultArray.count; j++) {
        NSString *str = resultArray[j];
        if (j == 0) {
            [paramsStr appendString:str];
        } else {
            [paramsStr appendFormat:@"&%@", str];
        }
    }
    //    NSLog(@"参数拼接:%@", paramsStr);
    
    return paramsStr;
}

/// 数组转为json字符串
+ (NSString *)arrayToJSONString:(NSArray *)array {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonResult;
}

#pragma mark - 网络请求

/// 网络请求方法
+ (void)requestWithUrlPath:(NSString *)path module:(NSString *)module interface:(NSString *)interface parameterDict:(NSDictionary *)parameterDict showLoading:(BOOL)showLoading success:(SuccessBlock)success failure:(FailureBlock)failure {
    if (showLoading) {
        [SVProgressHUD show];
    }
    NSDictionary *params = [self setupParamsDictWithModule:module interface:interface dataDict:parameterDict];
    [[HttpRequest sharedInstance] postWithUrlPath:path parameters:params success:^(id  _Nullable responseObject) {
        if (showLoading) {
            [SVProgressHUD dismiss];
        }
        if (success) {
            success(responseObject);
        }
    } failure:^(NSString * _Nullable errorCode, NSString * _Nullable errorText) {
        if (showLoading && !kStringIsEmpty(errorText)) {
            [SVProgressHUD showErrorWithStatus:errorText];
        }
        if (failure) {
            failure(errorCode, errorText);
        }
    }];
}

/// portal模块网络请求方法
+ (void)requestWithModule:(NSString *)module interface:(NSString *)interface parameterDict:(NSDictionary *)parameterDict showLoading:(BOOL)showLoading success:(SuccessBlock)success failure:(FailureBlock)failure {
    [self requestWithUrlPath:API_COMMON_PATH module:module interface:interface parameterDict:parameterDict showLoading:showLoading success:success failure:failure];
}

/// Shop模块网络请求方法
+ (void)shopRequestWithModule:(NSString *)module interface:(NSString *)interface parameterDict:(NSDictionary *)parameterDict showLoading:(BOOL)showLoading success:(SuccessBlock)success failure:(FailureBlock)failure {
    [self requestWithUrlPath:API_SHOP_PATH module:module interface:interface parameterDict:parameterDict showLoading:showLoading success:success failure:failure];
}

@end
